package net.pingfang.util;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * XXX
 *
 * @author: CM
 * @date: 2023/2/6
 */
@Slf4j
public class ShaUtil {

    /**
     * 利用java原生的摘要实现sha256加密
     *
     * @param str 加密后的报文
     * @return
     */
    public static String getsha256(String str) {
        MessageDigest messagedigest;
        String encodestr = "";
        try {
            messagedigest = MessageDigest.getInstance("sha-256");
            messagedigest.update(str.getBytes(StandardCharsets.UTF_8));
            encodestr = byte2hex(messagedigest.digest());
        } catch (Exception e) {
            log.error("change sha256error:{}", ExceptionUtil.getStackTrace(e));
        }
        return encodestr;
    }

    public static void main(String[] args) {
        System.out.println(getsha256("admin@123"));
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    private static String byte2hex(byte[] bytes) {
        StringBuilder stringbuffer = new StringBuilder();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xff);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringbuffer.append("0");
            }
            stringbuffer.append(temp);
        }
        return stringbuffer.toString();
    }
}
